using Microsoft.AspNetCore.Mvc;
using DatabaseManager.Models;
using DatabaseManager.Services;
using System.Text.Json;

namespace DatabaseManager.Controllers;

public class HomeController : Controller
{
    private readonly IAuthenticationService _authenticationService;

    public HomeController(IAuthenticationService authenticationService)
    {
        _authenticationService = authenticationService;
    }

    public IActionResult Index()
    {
        // 检查是否已登录
        if (HttpContext.Session.GetString("IsAuthenticated") == "true")
        {
            return RedirectToAction("DatabaseManagement");
        }
        
        return View();
    }

    public IActionResult DatabaseManagement()
    {
        // 检查是否已登录
        if (HttpContext.Session.GetString("IsAuthenticated") != "true")
        {
            return RedirectToAction("Login");
        }
        
        return View();
    }

    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Login(LoginViewModel model)
    {
        // 检查是否是 AJAX 请求
        bool isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
        
        if (ModelState.IsValid)
        {
            if (_authenticationService.ValidateCredentials(model.Username, model.Password))
            {
                // 设置会话
                HttpContext.Session.SetString("IsAuthenticated", "true");
                HttpContext.Session.SetString("Username", model.Username);
                
                if (isAjax)
                {
                    // AJAX 请求返回 JSON
                    return Json(new { 
                        success = true, 
                        message = "登录成功", 
                        redirectUrl = Url.Action("DatabaseManagement", "Home") 
                    });
                }
                else
                {
                    // 传统请求重定向
                    return RedirectToAction("DatabaseManagement");
                }
            }
            
            // 添加错误消息
            ModelState.AddModelError("", "用户名或密码错误");
        }
        
        if (isAjax)
        {
            // AJAX 请求返回错误信息
            var errors = ModelState.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
            );
            
            return Json(new { 
                success = false, 
                message = "用户名或密码错误",
                errors = errors
            });
        }
        else
        {
            // 传统请求返回视图
            return View(model);
        }
    }

    public IActionResult Logout()
    {
        HttpContext.Session.Clear();
        return RedirectToAction("Index");
    }
}